<template>
  <teleport to="body">
    <div v-if="visible" class="global-error-modal" @click="handleBackdropClick">
      <div class="error-content" @click.stop>
        <div class="error-header">
          <h3>系统错误详情</h3>
          <button class="close-btn" @click="close">
            <el-icon><Close /></el-icon>
          </button>
        </div>

        <div class="error-body">
          <div class="error-info">
            <div class="error-time">
              <strong>发生时间:</strong> {{ formatTime(errorInfo.timestamp) }}
            </div>
            <div class="error-type"> <strong>错误类型:</strong> {{ errorInfo.type }} </div>
            <div class="error-message">
              <strong>错误信息:</strong>
              <pre>{{ errorInfo.message }}</pre>
            </div>
            <div v-if="errorInfo.stack" class="error-stack">
              <strong>错误堆栈:</strong>
              <pre>{{ errorInfo.stack }}</pre>
            </div>
            <div v-if="errorInfo.componentStack" class="error-component">
              <strong>组件堆栈:</strong>
              <pre>{{ errorInfo.componentStack }}</pre>
            </div>
          </div>
        </div>

        <div class="error-actions">
          <div class="search-engines">
            <h4>快速搜索解决方案:</h4>
            <div class="search-buttons">
              <el-button @click="searchError('google')" type="primary" size="small">
                <el-icon><Search /></el-icon>
                Google 搜索
              </el-button>
              <el-button @click="searchError('baidu')" type="success" size="small">
                <el-icon><Search /></el-icon>
                百度搜索
              </el-button>
              <el-button @click="searchError('stackoverflow')" type="warning" size="small">
                <el-icon><Search /></el-icon>
                Stack Overflow
              </el-button>
              <el-button @click="searchError('github')" type="info" size="small">
                <el-icon><Search /></el-icon>
                GitHub Issues
              </el-button>
            </div>
          </div>

          <div class="action-buttons">
            <el-button @click="copyErrorInfo" size="small">
              <el-icon><DocumentCopy /></el-icon>
              复制错误信息
            </el-button>
            <el-button @click="reloadPage" type="primary" size="small">
              <el-icon><Refresh /></el-icon>
              重新加载页面
            </el-button>
            <el-button @click="close" size="small">关闭</el-button>
          </div>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Close, Search, DocumentCopy, Refresh } from '@element-plus/icons-vue';

  interface ErrorInfo {
    message: string;
    stack?: string;
    componentStack?: string;
    timestamp: number;
    type: string;
    url?: string;
    line?: number;
    column?: number;
  }

  const props = defineProps<{
    visible: boolean;
    errorInfo: ErrorInfo;
  }>();

  const emit = defineEmits<{
    close: [];
    reload: [];
  }>();

  // 格式化时间
  const formatTime = (timestamp: number) => {
    return new Date(timestamp).toLocaleString('zh-CN');
  };

  // 生成搜索关键词
  const getSearchKeywords = () => {
    const keywords = [];

    // 提取关键错误信息
    const message = props.errorInfo.message;
    if (message) {
      // 移除文件路径和行号
      const cleanMessage = message
        .replace(/at\s+.*?:\d+:\d+/g, '')
        .replace(/\s+/g, ' ')
        .trim();
      keywords.push(cleanMessage);
    }

    // 添加错误类型
    if (props.errorInfo.type && props.errorInfo.type !== 'Error') {
      keywords.push(props.errorInfo.type);
    }

    // 添加 Vue 相关关键词
    keywords.push('Vue 3', 'TypeScript');

    return keywords.filter((k) => k).join(' ');
  };

  // 搜索错误解决方案
  const searchError = (engine: string) => {
    const keywords = getSearchKeywords();
    let searchUrl = '';

    switch (engine) {
      case 'google':
        searchUrl = `https://www.google.com/search?q=${encodeURIComponent(keywords)}`;
        break;
      case 'baidu':
        searchUrl = `https://www.baidu.com/s?wd=${encodeURIComponent(keywords)}`;
        break;
      case 'stackoverflow':
        searchUrl = `https://stackoverflow.com/search?q=${encodeURIComponent(keywords)}`;
        break;
      case 'github':
        searchUrl = `https://github.com/search?q=${encodeURIComponent(keywords)}&type=issues`;
        break;
    }

    if (searchUrl) {
      window.open(searchUrl, '_blank');
    }
  };

  // 复制错误信息
  const copyErrorInfo = async () => {
    const errorText = `
错误时间: ${formatTime(props.errorInfo.timestamp)}
错误类型: ${props.errorInfo.type}
错误信息: ${props.errorInfo.message}
${props.errorInfo.stack ? `错误堆栈:\n${props.errorInfo.stack}` : ''}
${props.errorInfo.componentStack ? `组件堆栈:\n${props.errorInfo.componentStack}` : ''}
`.trim();

    try {
      await navigator.clipboard.writeText(errorText);
      ElMessage.success('错误信息已复制到剪贴板');
    } catch (err) {
      // 降级方案
      const textArea = document.createElement('textarea');
      textArea.value = errorText;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      ElMessage.success('错误信息已复制到剪贴板');
    }
  };

  // 重新加载页面
  const reloadPage = () => {
    emit('reload');
    window.location.reload();
  };

  // 关闭弹窗
  const close = () => {
    emit('close');
  };

  // 点击背景关闭
  const handleBackdropClick = () => {
    close();
  };
</script>

<style lang="scss" scoped>
  .global-error-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    padding: 20px;
  }

  .error-content {
    background: #fff;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    max-width: 900px;
    width: 100%;
    max-height: 85vh;
    overflow-y: auto;
    animation: errorModalSlide 0.2s ease-out;
  }

  @keyframes errorModalSlide {
    from {
      opacity: 0;
      transform: translateY(-20px) scale(0.95);
    }
    to {
      opacity: 1;
      transform: translateY(0) scale(1);
    }
  }

  .error-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
    background: #f5f7fa;

    h3 {
      margin: 0;
      color: #303133;
      font-size: 16px;
      font-weight: 500;
    }

    .close-btn {
      background: none;
      border: none;
      padding: 6px;
      cursor: pointer;
      border-radius: 2px;
      color: #909399;
      transition: all 0.2s;

      &:hover {
        background-color: #e4e7ed;
        color: #606266;
      }
    }
  }

  .error-body {
    padding: 20px;
    max-height: calc(85vh - 180px);
    overflow-y: auto;
  }

  .error-info {
    > div {
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }

      strong {
        display: block;
        margin-bottom: 8px;
        color: #303133;
        font-weight: 500;
        font-size: 13px;
      }

      pre {
        background-color: #f5f7fa;
        border: 1px solid #e4e7ed;
        padding: 12px;
        border-radius: 2px;
        font-size: 12px;
        line-height: 1.4;
        overflow-x: auto;
        white-space: pre-wrap;
        word-wrap: break-word;
        margin: 0;
        color: #606266;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      }
    }
  }

  .error-time {
    color: #909399;
    font-size: 13px;
  }

  .error-actions {
    padding: 16px 20px;
    border-top: 1px solid #e4e7ed;
    background: #fafafa;

    h4 {
      margin: 0 0 12px 0;
      font-size: 13px;
      color: #606266;
      font-weight: 500;
    }

    .search-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 16px;

      .el-button {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
      }
    }

    .action-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      justify-content: flex-end;

      .el-button {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .global-error-modal {
      padding: 10px;
    }

    .error-content {
      max-height: 90vh;
    }

    .error-header {
      padding: 16px 16px 0;

      h3 {
        font-size: 16px;
      }
    }

    .error-body {
      padding: 16px;
    }

    .error-actions {
      padding: 0 16px 16px;

      .search-buttons,
      .action-buttons {
        justify-content: center;
      }
    }

    .error-info pre {
      font-size: 11px;
      padding: 10px;
    }
  }
</style>
